//
//  ST_ModifyMyLikeTraitViewController.swift
//  btvideo
//
//  Created by mac on 2020/7/7.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SwiftyUserDefaults
import MJRefresh


/**
 修改喜欢特质
 */
class ST_ModifyMyLikeTraitViewController: ST_BTLightBarViewController {
    
    
    var refresh_closure:(()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.white
        
        
        
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "至少选择4个你喜欢的特质")
        
        
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        view.addSubview(label)
        
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(43-20+statusBarHeight)
        }
        
        
        
        let label1 = UILabel()
        let attrString1 = NSMutableAttributedString(string: "你的选择会影响特质对对碰和伴心丘比特的配对")
        let attr1: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)]
        attrString1.addAttributes(attr1, range: NSRange(location: 0, length: attrString1.length))
        label1.attributedText = attrString1
        
        
        view.addSubview(label1)
        label1.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(label.snp.bottom).offset(5)
        }
        
         
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(label1.snp.bottom).offset(10)
        }
        
        
        view.addSubview(love_btn)
        love_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-25-BTSafeAreaBottom)
            make.width.equalTo(260)
            make.height.equalTo(40)
        }
        
        
        self.request_data()
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,"size":100] as [String : Any]
        
        JVrequest(PH.registerFeatureListApi,parameters:param, success: { (json) in
            
            print("注册特质详情:",json)
            
            let dataStr = json["data"].rawString() ?? ""
            
            if let aArray = [ST_PeculiarityModel].deserialize(from: dataStr) as? [ST_PeculiarityModel]{
                

                self.data_array = aArray
                
                self.selectedIds = aArray.filtered({ (m) -> Bool in
                    return m.isSelected
                }) { (pModel) -> String in
                    return pModel.id.string
                }
                
            }else{
                self.selectedIds.removeAll()
                self.data_array.removeAll()
            }
            
            self.collectionView.reloadData()
            self.update_love_btn_status()
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }
    
    //     MARK: - Properties
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 30
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 15, bottom: BTSafeAreaBottom + 79, right: 15)
        let w = (ScreenWidth - 15*4)/3
        controlLayout.itemSize = CGSize.init(width: w, height: w+31+20)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_ModifyMyLikeTraitCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.white
        
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        control.allowsMultipleSelection = true
        return control
    }()
    
    fileprivate var data_array = [ST_PeculiarityModel]()
    
    fileprivate lazy var love_normal_back_image = UIImage.init(color: UIColor.init(hexString: "#DFE3E9")!, size: CGSize.init(width: 1, height: 1))
    
    fileprivate lazy var love_selected_back_image = UIImage.init(color: UIColor.init(hexString: "#FEC207")!, size: CGSize.init(width: 1, height: 1))
    
    
    fileprivate lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.set_back_image_for_all_states(love_normal_back_image)
        control.setBackgroundImage(love_selected_back_image, for: UIControl.State.selected)
        control.cornerRadius = 20
        control.setTitleForAllStates("至少选择4个特质")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var selectedIds = [String]()
  
}

extension ST_ModifyMyLikeTraitViewController{
    
    @objc func love_handle(){
        
        if !love_btn.isSelected{
            return
        }
        
        let ids = selectedIds.joined(separator: ",")
        
        JVrequest(PH.selectedFeatureListApi,parameters: ["features":ids], success: { (json) in
            
            
            self.refresh_closure?()
            
            self.goback_previous_controller()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
    }
    
    fileprivate func update_love_btn_status(){
        
        love_btn.isSelected = selectedIds.count >= 4
        
        if love_btn.isSelected{
            love_btn.setTitleForAllStates("选好了")
        }else{
            love_btn.setTitleForAllStates("至少选择4个特质")
        }
        
    }
}

extension ST_ModifyMyLikeTraitViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    // MARK: UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ModifyMyLikeTraitCell.self, for: indexPath)
        
        cell.child_model = data_array[indexPath.item]
        
        cell.topone_image_view.isHidden = indexPath.item != 0
        
        
        cell.click_closure = { iCell in
            
            guard let m = iCell.child_model else{return}
            
            if m.isSelected{
                self.selectedIds.append(m.id.string)
            }else{
                self.selectedIds.removeFirst(where: {$0 == m.id.string})
            }
            self.update_love_btn_status()
        }
        
        return cell
    }
    
    
    
    // MARK: UICollectionViewDelegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
}



//MARK:- Cell
fileprivate class ST_ModifyMyLikeTraitCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(cover_image_view)
        contentView.addSubview(titleLabel)
        contentView.addSubview(content_label)
        
        cover_image_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(cover_image_view.snp.width)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(cover_image_view.snp.bottom).offset(15)
            make.centerX.equalTo(cover_image_view)
        }
        
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(1)
            make.centerX.equalTo(cover_image_view)
        }
        
        cover_image_view.addSubview(coverMask)
        coverMask.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        coverMask.addSubview(cover_selected_mask)
        cover_selected_mask.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        contentView.addSubview(topone_image_view)
        topone_image_view.snp.makeConstraints { (make) in
            make.bottom.equalTo(cover_image_view.snp.top).offset(13)
            make.centerX.equalToSuperview()
        }
        
        contentView.addSubview(love_btn)
        love_btn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //    MARK: - Properties
    fileprivate lazy var coverMask:UIView = {
        let control = UIView()
        control.backgroundColor = Color.init(white: 0, alpha: 0.4)
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var cover_selected_mask:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("个人中心_icon_选择sel")
        return control
    }()
    
    lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 20
        return control
    }()
    
    lazy var topone_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("topOne")!)
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#ACB4C0")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.addTarget(self, action: #selector(click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    var click_closure:((ST_ModifyMyLikeTraitCell)->())?
    
    @objc fileprivate func click_handle(){
        

        guard let m = self.child_model else {
            return
        }
        self.child_model?.isSelected = !m.isSelected
        
        coverMask.isHidden = !m.isSelected
        
        self.click_closure?(self)
        
    }
    
    //    MARK:-
    weak var child_model:ST_PeculiarityModel?{
        didSet{
            
            guard let child_model = child_model else {
                return
            }
            
            coverMask.isHidden = !child_model.isSelected
            
            cover_image_view.pin_setImage(from: child_model.image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = child_model.name
            
            
            
            if let sex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex,sex == .male{
                content_label.text = child_model.own_num.st_number_description() + "个女生"
            }else{
                content_label.text = child_model.own_num.st_number_description() + "个男生"
            }
            
        }
    }
    
}
